﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using ProgNetComponentsDx.Mode;
using ProgNetComponentsDx.Options;
using ProgNetComponentsDx.Browsers;
using System.Reflection;
using ProgNetComponents.Data.SqlCe;
using ProgNetComponents.Classes;

namespace BuildHelper.Setup.Brancze
{
    public partial class FormBrancz : MyBaseSqlCeForm
    {
        private static SqlCeDataManager _Manager;
        private static SqlCeDataManager Manager
        {
            get
            {
                if (_Manager == null)
                {
                    _Manager = new SqlCeDataManager();
                    _Manager.AutoLogExceptions = true;
                }
                return _Manager;
            }
        }
        

        public FormBrancz()
        {
            InitializeComponent();
        }
        public FormBrancz(string brancz)
        {
            InitializeComponent();
            CurrentRecord = brancz;
        }
        protected override bool GetRecord()
        {
            bool res = base.GetRecord();
           
            return res;
        }
        protected override bool NewRecord()
        {
            bool res = base.NewRecord();
            if (res)
            {

#region init
                string[] apps = new string[]{
                    "GENESDK",
                    "GCM",
                    "BIO",
                    "MOL",
                    "CTG",
                    "FLW",
                    "DXP",
                    "ACC",
                    "HLA",
                    "GLAB",
                    "IDX"
                };
                string[] sln = new string[]{
                    @"%ROOT%\nd_src\GENE\apps\genesdk\src\GeneAnalyzer\SoftGeneSDK.sln",
                    @"%ROOT%\nd_src\GENE\apps\gcm\src\gui\SoftGcm\SoftGcm.sln",
                    @"%ROOT%\nd_src\GENE\apps\bio\src\gui\SoftBioChem\SoftBioChemistry.sln",
                    @"%ROOT%\nd_src\GENE\apps\mol\src\gui\SoftMolecular\SoftMolecular.sln",
                    @"%ROOT%\nd_src\GENE\apps\ctg\src\gui\SoftGen\SoftGen.sln",
                    @"%ROOT%\nd_src\GENE\apps\flw\src\gui\SoftFlowcytometry\SoftFlowcytometry.sln",
                    @"%ROOT%\nd_src\GENE\apps\dxp\src\gui\SoftDxPath\SoftDxPath.sln",
                    @"%ROOT%\nd_src\GENE\apps\acc\src\gui\SoftPreAnalytical\SoftPreAnanlytical.sln",
                    @"%ROOT%\nd_src\GENE\apps\hla\src\gui\SoftHla\SoftHla.sln",
                    @"%ROOT%\nd_src\GENE\apps\glab\src\gui\SoftLab\SoftLab.sln",
                    ""
                };
                string[] dist = new string[]{
                    @"%ROOT%\nd_src\GENE\apps\genesdk\dist",
                    @"%ROOT%\nd_src\GENE\apps\gcm\dist\gui",
                    @"%ROOT%\nd_src\GENE\apps\bio\dist\gui",
                    @"%ROOT%\nd_src\GENE\apps\mol\dist\gui",
                    @"%ROOT%\nd_src\GENE\apps\ctg\dist\gui",
                    @"%ROOT%\nd_src\GENE\apps\flw\dist\gui",
                    @"%ROOT%\nd_src\GENE\apps\dxp\dist\gui",
                    @"%ROOT%\nd_src\GENE\apps\acc\dist\gui",
                    @"%ROOT%\nd_src\GENE\apps\hla\dist\gui",
                    @"%ROOT%\nd_src\GENE\apps\glab\dist\gui",
                    ""
                };

                string[] exe = new string[]{
                    "",
                    "",
                    @"%ROOT%\nd_src\GENE\apps\bio\dist\gui\SoftBioChem.exe",
                    @"%ROOT%\nd_src\GENE\apps\mol\dist\gui\SoftMolecular.exe",
                    @"%ROOT%\nd_src\GENE\apps\ctg\dist\gui\SoftGene.exe",
                    @"%ROOT%\nd_src\GENE\apps\flw\dist\gui\SoftFlowcytometry.exe",
                    @"%ROOT%\nd_src\GENE\apps\dxp\dist\gui\SoftDxPath.exe",
                    @"%ROOT%\nd_src\GENE\apps\acc\dist\gui\SoftPreAnalytical.exe",
                    @"%ROOT%\nd_src\GENE\apps\hla\dist\gui\SoftHla.exe",
                    @"%ROOT%\nd_src\GENE\apps\glab\dist\gui\SoftLab.exe",
                    ""
                };
#endregion
                for (int i = 0; i < apps.Length; i++)
                {
                    branczeDataSet.STP_BRANCZE_APPS.AddSTP_BRANCZE_APPSRow("", sln[i], dist[i], exe[i], apps[i], i);
                }
            }

            return res;
        }

        protected override void UpdateCurrentRecordAfterSave()
        {
            CurrentRecord = MainRow["STP_BR_NAZWA"].AsString();
        }
        protected override bool ValidateAll()
        {
            return base.ValidateAll() && branczeDataSet.STP_BRANCZE_APPS.ValidateColUnique("STP_BR_APP_APP", "Projekt powinien byc unikalny");
        }
        private string Brancz
        {
            get { return sTP_BR_NAZWATextEdit.EditValue.AsString(); }
        }

        protected override void FinishEdit()
        {
            base.FinishEdit();
            foreach (DataRow r in branczeDataSet.STP_ZMIENNE.Rows)
            {
                if (r.CanRead())
                    r.SetColVal("STP_ZM_BRANCZ", Brancz);
            }
            foreach (DataRow r in branczeDataSet.STP_BRANCZE_APPS.Rows)
            {
                if (r.CanRead())
                    r.SetColVal("STP_BR_APP_BRANCZ", Brancz);
            }
        }
        protected override void CopyRecord()
        {
            base.CopyRecord();
            sTP_BR_SVNButtonEdit.EditValue = DBNull.Value;
            sTP_BR_KATALOGButtonEdit.EditValue = DBNull.Value;
            sTP_BR_DRIVETextEdit.EditValue = DBNull.Value;
            sTP_BR_NAZWATextEdit.EditValue = DBNull.Value;
        }
        
        protected override bool Save()
        {
            bool IsNew = modeProvider1.CurrentMode == ProgNetComponentsDx.Enums.FormMode.New;
            string oldDrive = string.Empty;
            if (MainRow.CanRead() && MainRow.RowState != DataRowState.Added)
            {
                oldDrive = MainRow["STP_BR_DRIVE", DataRowVersion.Original].AsString();
            }
            bool res = base.Save();
            string newDrive = sTP_BR_DRIVETextEdit.EditValue.AsString();
            if (res)
            {
                if (oldDrive.IsNotNull() && oldDrive!=newDrive)
                    Brancze.BranczeTools.UnSubstDrive(oldDrive);
                if(newDrive.IsNotNull() && oldDrive!=newDrive)
                    Brancze.BranczeTools.SubstDrive(newDrive, this.sTP_BR_KATALOGButtonEdit.EditValue.AsString());
            }
            if (res && IsNew)
            {
                string opt = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.Brancze.AutoCheckOut);
                bool checkout = false;
                if (opt == YesNoAsk.YES)
                    checkout = true;
                if (opt == YesNoAsk.ASK)
                    checkout = this.ShowDxYNQuestionDialog("Czy chcesz wykonać CheckOut?") == System.Windows.Forms.DialogResult.Yes;
                if (checkout)
                {
                    GlobalTools.TortoiseTools.SvnCheckOutUpdate(this.sTP_BR_NAZWATextEdit.EditValue.AsString(), true);
                }
            }
            
            return res;
        }
        private void SLNButtonEdit_EditValueChanged(object sender, EventArgs e)
        {
            FormatEdit(sender);
        }
        private void EXEButtonEdit_EditValueChanged(object sender, EventArgs e)
        {
            FormatEdit(sender);
        }
        private void DISTButtonEdit_EditValueChanged(object sender, EventArgs e)
        {
            FormatEdit(sender);
        }

        private void FormatEdit(object sender)
        {
            BaseEdit ed = sender as BaseEdit;
            if (ed != null)
            {
                string val = ed.EditValue.AsString();
                if (val.IsNotNull())
                {
                    string val2 = GetFormatedPath(val);
                    if (val2 != val)
                    {
                        ed.EditValue = val2;
                    }
                }
            }
        }
        
        private string GetFormatedPath(string path)
        {
            string res = path;
            string root = distDialog.RootPath.AsString().TrimEnd('\\');

            if (root.IsNotNull() && path.XMatch("^" + root.XEscape()))
            {
                res = distDialog.RootName + "\\" + path.XReplace("^" + root.XEscape(), "").TrimStart('\\');
            }
            return res;
        }
        private string GetFullPath(string path)
        {
            string res = path;
            string root = distDialog.RootPath.AsString().TrimEnd('\\');

            if (root.IsNotNull() && path.XMatch("^" + distDialog.RootName.XEscape()))
            {
                res = root + "\\" + path.XReplace("^" + distDialog.RootName.XEscape(), "").TrimStart('\\');
            }
            return res;
        }

        private void SLNButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            BaseEdit ed = sender as BaseEdit;
            if (ed != null)
            {
                if (ed.Properties.ReadOnly)
                    return;
                
                slnDialog.FileName = GetFullPath(ed.EditValue.AsString());

                try
                {
                    slnDialog.InitialDirectory = System.IO.Path.GetDirectoryName(slnDialog.FileName);
                }
                catch { }

                if (slnDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ed.EditValue = slnDialog.FileName;
                }
            }
        }

        private void DISTButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if ((sender as BaseEdit).Properties.ReadOnly)
                return;
            distDialog.Path = (sender as BaseEdit).EditValue.AsString();
            if (distDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                (sender as BaseEdit).EditValue = distDialog.Path;
            }
        }

        private void EXEButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            BaseEdit ed = sender as BaseEdit;
            if (ed != null)
            {
                if (ed.Properties.ReadOnly)
                    return;
                exeDialog.FileName = GetFullPath(ed.EditValue.AsString());
                try
                {
                    exeDialog.InitialDirectory = System.IO.Path.GetDirectoryName(exeDialog.FileName);
                }
                catch { }
                if (exeDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ed.EditValue = exeDialog.FileName;
                }
            }
        }

        private void sTP_BR_KATALOGButtonEdit_EditValueChanged(object sender, EventArgs e)
        {
            distDialog.RootPath = sTP_BR_KATALOGButtonEdit.EditValue.AsString();
        }

        private void sTP_BR_SVNButtonEdit_EditValueChanged(object sender, EventArgs e)
        {
            string str = sTP_BR_SVNButtonEdit.EditValue.AsString();
            if (str.IsNotNull() && modeProvider1.CurrentMode == ProgNetComponentsDx.Enums.FormMode.New)
            {
                sTP_BR_NAZWATextEdit.EditValue = str;
                string katalogBranczy = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Brancze.DomyslnyKatalogBranczy).TrimEnd('\\');
                if (katalogBranczy.IsNotNull())
                    sTP_BR_KATALOGButtonEdit.EditValue = katalogBranczy + "\\" + str;
            }
        }

        private void sTP_BR_CONFIGButtonEdit_Settings_CreateNewRow(object sender, CreateNewRowEventArgs e)
        {
            Konfigi.KonfigiDataSet ds = new Konfigi.KonfigiDataSet();
            Manager.AddTableDef(ds.STP_KONFIGI);
            if (e.DisplayValue.IsNotNull())
            {
                e.NewRow["GS_CFG_NAZWA"] = e.DisplayValue;
                ds.STP_KONFIGI.AddSTP_KONFIGIRow(e.DisplayValue);
                Manager.UpdateDataSet(ds);
            }
        }

        private void sTP_BR_KATALOGButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (sTP_BR_KATALOGButtonEdit.Properties.ReadOnly)
                return;
            folderBrowserDialog1.SelectedPath = sTP_BR_KATALOGButtonEdit.EditValue.AsString();

            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                sTP_BR_KATALOGButtonEdit.EditValue = folderBrowserDialog1.SelectedPath;
            }
        }

        private void btnZmien_Click(object sender, EventArgs e)
        {
            ObjectDialogResult dlg = BrowserCache.ShowBrowserDialog(Init.InitFormBrowserNames.Statyczne.FreeDrives);
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                sTP_BR_DRIVETextEdit.EditValue = dlg.Value;
            }
        }

        private void bntCzysc_Click(object sender, EventArgs e)
        {
            sTP_BR_DRIVETextEdit.EditValue = "";
        }

        private void positionControl1_OrderChanged(object sender, EventArgs e)
        {
            DataRow[] rows = branczeDataSet.STP_BRANCZE_APPS.Select();
            foreach (DataRow r in rows)
            {
                if (r.RowState == DataRowState.Modified)
                    changeDetectorProvider1.CheckChanges(r, r["STP_BR_APP_POZYCJA", DataRowVersion.Original], r["STP_BR_APP_POZYCJA"]);
            }
        }

        private void modeProvider1_CustomGetModes(object sender, CustomModeSettingsEventArgs e)
        {
            if (sender == colSTP_BR_APP_SLN ||
                sender == colSTP_BR_APP_DIST)
            {
                if (e.Row != null)
                {
                    if (!browserProvider1.GetSettings(rep_STP_BR_APP_APP).Browser.GetColumnValueForEditValue(e.Row["STP_BR_APP_APP"], "STP_APP_IS_GUI").AsBool())
                        e.IsRequired = false;
                }
            }
        }

    }
}
